﻿using FFIV.Lib.BusinessRules;
using FFIV.Lib.IView.Categories;
using FFIV.Lib.Model;
using FFIV.Lib.Utilities;

namespace FFIV.Lib.Controlers.Admin
{
	public class ManageCategoriesController
	{
		private readonly IManageCategories m_View;

		public ManageCategoriesController(IManageCategories view)
		{
			m_View = view;
		}

		public void LoadPage()
		{
			m_View.Categories = CategoriesUtility.GetCategories();
		}

		public void AddCategory()
		{
			CategoriesRules.AddCategory(m_View.ModifiedCategoryName, 0, m_View.ModifiedCategoryParentId);

			ReloadCategories();
		}

		public void AddChildCategory()
		{
			if (m_View.ModifiedCategoryId != 0)
			{
				CategoriesRules.AddCategory(m_View.ModifiedCategoryName, 0, m_View.ModifiedCategoryId);

				ReloadCategories();
			}
		}

		public void EditCategory()
		{
			if (m_View.ModifiedCategoryId != 0)
			{
				CategoriesRules.UpdateCategory(m_View.ModifiedCategoryId, m_View.ModifiedCategoryName);

				ReloadCategories();
			}
		}

		public void DeleteCategory()
		{
			if (m_View.ModifiedCategoryId != 0)
			{
				DeleteCategory(CategoriesUtility.GetCategoryNodeById(m_View.ModifiedCategoryId));

				ReloadCategories();
			}
		}

		private void DeleteCategory(CategoryNode parent)
		{
			foreach (CategoryNode node in parent.Children)
			{
				DeleteCategory(node);
			}

			CategoriesRules.DeleteCategoryById(parent.Id);
		}

		private void ReloadCategories()
		{
			// 使得分类树缓存失效
			CategoriesUtility.IsCategoryCacheAble = false;
			// 更新刷新界面
			LoadPage();
		}
	}
}
